package game.controller;

import game.model.Block;
import game.model.Board;


public class NormalMerge implements MergeRule {
    @Override
    public boolean mergeBlocks(final Board board, Direction direction) {
        // 处理时，程序会依次逆时针旋转 90 度，旋转第 cnt 次前调用 moveLeft
        int cnt;
        if (direction == Direction.LEFT) cnt = 1;
        else if (direction == Direction.UP) cnt = 2;
        else if (direction == Direction.RIGHT) cnt = 3;
        else if (direction == Direction.DOWN) cnt = 4;
        else return false;

        // 开始处理
        boolean ret = false;
        // 拷贝一份
        Board nexBoard = new Board(board.getWidth(), board.getHeight());
        nexBoard.copiedBy(board);
        // 依次逆时针旋转 90 度
        for (int i = 1; i <= 4; ++i) {
            if (cnt == i) ret = this.mergeLeft(nexBoard);
            nexBoard = Board.rotateBoard90Degree(nexBoard);
        }
        board.copiedBy(nexBoard);
        return ret;
    }


    /**
     * 对指定棋盘执行操作：向左合并方块
     *
     * @param board
     * @return 是否有方块成功合并
     */
    private boolean mergeLeft(Board board) {
        int cnt = 0;
        for (int y = 0; y < board.getHeight(); ++y) {
            for (int x = 1; x < board.getWidth(); ++x) {
                try {
                    int l = board.getBlock(x - 1, y).getNumber(), r = board.getBlock(x, y).getNumber();
                    if (l == r) { // 可以合并
                        board.setBlock(x, y, null);
                        board.setBlock(x - 1, y, new Block(l + r));
                        ++cnt;
                    }
                } catch (NullPointerException ex) { // 是空 Block，跳过即可
                }
            }
        }
        return cnt > 0;
    }
}
